<?php

namespace App\Services;

use App\Models\RsUsers;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redis;

class AuthService extends BaseService
{
    /**
     * 登录用的url地址
     */
    const LOGIN_URL = 'http://9.23.28.52:7001/mobilelogin.action';

    /**
     * 用户登陆
     * @param array $parameters
     * @return array
     * @auth smile
     */
    public function login(array $parameters): array
    {
        try{

            $response = Http::asForm()->post(self::LOGIN_URL,[
                'username' => $parameters['username'],
                'password' => $parameters['password']
            ]);

            if ($response->successful()) {
                $result = $response->json();

                if ($result['success'] == true) {
                    if(!empty($result['sectionUid'])) {
                        $user = User::find($result['sectionUid']);

                        $token = auth('api')->login($user);

                        //$this->createMobile($user);

                        //将token的值保存到redis中
                        Redis::setex('token_'.$parameters['username'],config('jwt.ttl'),'Bearer '.$token);

                        return customer_return_success('登陆成功',[
                            'token' => 'Bearer '.$token
                        ]);
                    }
                }
            }

            return customer_return_error('账号或密码错误');
        }catch (\Exception $exception) {
            Log::channel('api')
                ->info('登陆异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('登陆失败，请稍后再试');
        }
    }

    /**
     * 用户登陆
     * @param array $parameters
     * @return array
     * @auth smile
     */
    public function loginByUsername(array $parameters): array
    {
        try{
            $user = User::where(['username'=>$parameters['username']])->first();
            if(empty($user)){

                return customer_return_error('用户不存在');
                
            }else {
                $token = auth('api')->login($user);

                //$this->createMobile($user);

                //将token的值保存到redis中
                Redis::setex('token_' . $parameters['username'], config('jwt.ttl'), 'Bearer ' . $token);

                return customer_return_success('登陆成功', [
                    'token' => 'Bearer ' . $token
                ]);
            }

            return customer_return_error('账号或密码错误');
        }catch (\Exception $exception) {
            Log::channel('api')
                ->info('登陆异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('登陆失败，请稍后再试');
        }
    }

    /**
     * 登录成功，保存数据到mobile表
     * @param User $user
     */
    public function createMobile(User $user)
    {
        try {
            if (!RsUsers::where('user_id',$user->id ?? 0)->exists()) {
                RsUsers::create([
                    'user_id'     => $user->id ?? 0,
                    'loginname'   => $user->username ?? '',
                    'username'    => $user->person->name ?? '',
                    'create_time' => date("Y-m-d H:i:s",time())
                ]);
            }
        }catch (\Error|\Exception|\Throwable $exception) {
            Log::channel('api')
                ->info('登陆异常：'.$exception->getMessage());

            report($exception);
        }
    }

    /**
     * 验证接口
     * @param string $authorization
     * @return array
     */
    public function check(string $authorization) : array
    {
        try {
            $key = 'token_'.auth('api')->user()->username;

            if (Redis::get($key) && (Redis::get($key) == $authorization)) {
                return customer_return_success('success');
            }

            return [
                'status'  => 'error',
                'code'    => 200,
                'message' => '你的账号已在别处登录，请及时修改密码',
                'data'    => []
            ];
        }catch (\Exception $exception) {
            Log::channel('api')
                ->info('验证接口异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 获取到用户的个人信息
     * @return mixed
     */
    public function user(): array
    {
        try{
            $person = auth('api')->user()->person;

            if (!is_null($person)) {
                $unit = $person->unit;
            } else {
                $unit = null;
            }

            $data = [
                'user' => [
                    'phone'       => $person->mobile ?? '',
                    'name'        => $person->name ?? '',
                    'department'  => $unit->name ?? ''
                ]
            ];

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('获取用户信息异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 安全退出
     * @return array
     */
    public function logout(): array
    {
        try{
            auth('api')->logout();

            return customer_return_success('安全退出');
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('退出登陆异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('退出失败，请稍后再试');
        }
    }
}
